﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Microsoft.Xna.Framework;

namespace SpaceFight.Units.Steering
{
	class Face : Align
	{
		private SteeringInfo.InfoType m_neededInfo = SteeringInfo.InfoType.Target                |
		                                             SteeringInfo.InfoType.MaxAngularAcceleration|
		                                             SteeringInfo.InfoType.MaxAngularSpeed       |
		                                             SteeringInfo.InfoType.AlignTargetRadius     |
		                                             SteeringInfo.InfoType.AlignSlowRadius       |
		                                             SteeringInfo.InfoType.AlignTimeToTarget     |
		                                             SteeringInfo.InfoType.ModelFrontVector;
		
		public override void GetSteering(IUnit p_unit, SteeringOutput p_steeringOutput)
		{
			if(HasValidInput(p_steeringOutput, p_unit, m_neededInfo) == false)
			{
				return;
			}
			
			// calculate steering
			Vector3 targetPosition = p_unit.SteeringInfo.Target.Position;
			GetSteering(ref targetPosition, p_unit, p_steeringOutput);
		}
		
		protected void GetSteering(ref Vector3 p_targetPosition, IUnit p_unit, SteeringOutput p_steeringOutput)
		{
			// direction to the target
			Vector3 direction = p_targetPosition - p_unit.Position;
			
			//check for zero direction
			if(direction.LengthSquared() == 0) return;
			direction.Normalize();
			Vector3 neutralDirection = p_unit.SteeringInfo.ModelFrontVector;
			Quaternion targetOrientation = QuaternionHelpers.AngleBetween(
					ref neutralDirection,
					ref direction);
			
			// get the naive direction to the target
			Quaternion rotation = p_unit.Orientation;
			rotation.Conjugate();
			rotation = rotation * targetOrientation;
			
			// delegate to Align
			base.GetSteering(ref rotation, ref p_unit, p_steeringOutput);
		}
	}
}
